package com.mz361.stdapi.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.mz361.common.data.PageSort;
import com.mz361.common.enums.StatusEnum;
import com.mz361.common.utils.RedisUtil;
import com.mz361.common.utils.StringUtil;
import com.mz361.stdapi.domain.StandardNotice;
import com.mz361.stdapi.domain.StandardNoticeObj;
import com.mz361.stdapi.repository.StandardNoticeRepository;
import com.mz361.stdapi.service.StandardNoticeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author niceale
 * @ date 2024/04/26
 */
@Service
public class StandardNoticeServiceImpl implements StandardNoticeService {


    @Autowired
    private StandardNoticeRepository standardNoticeRepository;

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 根据ID查询数据
     *
     * @param id 主键ID
     */
    @Override
    public StandardNotice getById(Long id) {
        return standardNoticeRepository.findById(id).orElse(null);
    }

    @Override
    public StandardNotice getByStandardNoticeNo(String standardNoticeNo) {
        String md5str = StringUtil.md5(standardNoticeNo);
        StandardNotice standardNotice;
        if (!redisUtil.hexists("STANDARD:NOTICE:INFO", md5str)) {
            standardNotice = standardNoticeRepository.getStandardNoticeByStandardNoticeNo(standardNoticeNo);
            redisUtil.hSet("STANDARD:NOTICE:INFO", md5str, JSONObject.toJSONString(standardNotice));
        } else {
            standardNotice = JSONObject.parseObject(redisUtil.hGet("STANDARD:NOTICE:INFO", md5str), StandardNotice.class);
        }
        return standardNotice;
    }

    @Override
    public List<StandardNotice> getStandardNotices() {
        return standardNoticeRepository.findAll();
    }

    /**
     * 获取分页列表数据
     *
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<StandardNotice> getPageList(Example<StandardNotice> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return standardNoticeRepository.findAll(example, page);
    }

    @Override
    public Page<StandardNoticeObj> getPageList(String noticeType, String keyWord, Integer pageNo, Integer pageSize) {
        //处理默认值
        pageNo = pageNo == null ? 0 : pageNo;
        pageSize = pageSize == null ? 8 : pageSize;
        noticeType = StringUtil.isEmpty(noticeType) ? "0" : noticeType;

        String md5str = StringUtil.md5("md5:" + noticeType + "," + keyWord + "," + pageNo + "," + pageSize);
        PageRequest page = PageRequest.of(pageNo, pageSize, Sort.Direction.DESC, "publishDate");
        if (!redisUtil.exists("STANDARD:NOTICE:" + md5str)) {
            Page<StandardNoticeObj> standardNoticeObjPage;
            if (StringUtil.notEmpty(keyWord)) {
                keyWord = "%" + keyWord + "%";
                standardNoticeObjPage = standardNoticeRepository.findProjectedEntitiesLikeKeyword(noticeType, keyWord, page);
            } else {
                standardNoticeObjPage = standardNoticeRepository.findProjectedEntities(noticeType, page);
            }
            if (standardNoticeObjPage != null && !standardNoticeObjPage.getContent().isEmpty()) {
                redisUtil.setexValue("STANDARD:NOTICE:" + md5str, 300, JSONObject.toJSONString(standardNoticeObjPage));
            }
            return standardNoticeObjPage;
        } else {
            return convertJsonStringToPage(redisUtil.getValue("STANDARD:NOTICE:" + md5str), page);
        }

    }

    /**
     * 保存数据
     *
     * @param standardNotice 实体对象
     */
    @Override
    public StandardNotice save(StandardNotice standardNotice) {
        standardNotice = standardNoticeRepository.save(standardNotice);
        return standardNotice;
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return standardNoticeRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    public static Page<StandardNoticeObj> convertJsonStringToPage(String jsonString, Pageable pageable) {
        // 解析JSON字符串为JSONObject
        JSONObject jsonObject = JSON.parseObject(jsonString);

        // 假设JSON对象中有一个名为"content"的字段，它是一个包含StandardPlan对象的数组
        JSONArray jsonArray = jsonObject.getJSONArray("content");
        Long totalElements = jsonObject.getLong("totalElements");

        // 创建StandardNotice列表
        List<StandardNoticeObj> standardNotices = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject jsonObj = jsonArray.getJSONObject(i);
            // 将每个JSONObject转换为StandardPlan对象，这里需要自定义转换逻辑
            StandardNoticeObj standardNotice = JSONObject.parseObject(jsonObj.toJSONString(), StandardNoticeObj.class);
            standardNotices.add(standardNotice);
        }

        // 创建Page对象
        return new PageImpl<>(standardNotices, pageable, totalElements);
    }


}
